package com.bkgy.controller.acidefficiency.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.commom.model.Temp;
import com.bkgy.controller.acidefficiency.dao.AcidEfficiencyDao;
import com.bkgy.controller.acidefficiency.entity.*;
import com.bkgy.controller.acidefficiency.entity.pdo.SteelGradeRateRes;
import com.bkgy.controller.acidefficiency.service.AcidEfficiencyService;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.ExcelUtilsPOI;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 2280酸轧效率分析服务实现类
 */
@Slf4j
@Service
public class AcidEfficiencyServiceImpl extends ServiceImpl<AcidEfficiencyDao, TbTcm22280ProSpeed> implements AcidEfficiencyService {
    @Autowired
    private AcidEfficiencyDao acidEfficiencyDao;

    @Override
    public ResultData getAcidEfficiency(AcidEfficiency request) {
        try {
            return ResultData.ResultDataSuccess(acidEfficiencyDao.getAcidEfficiency(request));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    @Override
    public ResultData getAcidEfficiencyList(AcidEfficiencyListReq request) {
        try {
            request.setPageIndex(0);
            request.setPageSize(5);
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<AcidEfficiencyListResp> list = acidEfficiencyDao.getAcidEfficiencyList(page, request);
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getHeadToCutterTime() != null) {
                    list.get(i).setHeadToCutterTime(list.get(i).getHeadToCutterTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getArriveWaitPosTime() != null) {
                    list.get(i).setArriveWaitPosTime(list.get(i).getArriveWaitPosTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getAnotherheadToweldTime() != null) {
                    list.get(i).setAnotherheadToweldTime(list.get(i).getAnotherheadToweldTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getTailToweldTime() != null) {
                    list.get(i).setTailToweldTime(list.get(i).getTailToweldTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getFinishedWeldTime() != null) {
                    list.get(i).setFinishedWeldTime(list.get(i).getFinishedWeldTime().setScale(0, RoundingMode.HALF_UP));
                }

            }
//            Integer count = acidEfficiencyDao.getAcidEfficiencyCount(request);
            return ResultData.ResultDataSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }

    }

    @Override
    public ResultData getAcidEfficiencyLists(AcidEfficiencyListReq request) {
        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<AcidEfficiencyListResp> list = acidEfficiencyDao.getAcidEfficiencyLists(page, request);
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getHeadToCutterTime() != null) {
                    list.get(i).setHeadToCutterTime(list.get(i).getHeadToCutterTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getArriveWaitPosTime() != null) {
                    list.get(i).setArriveWaitPosTime(list.get(i).getArriveWaitPosTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getAnotherheadToweldTime() != null) {
                    list.get(i).setAnotherheadToweldTime(list.get(i).getAnotherheadToweldTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getTailToweldTime() != null) {
                    list.get(i).setTailToweldTime(list.get(i).getTailToweldTime().setScale(0, RoundingMode.HALF_UP));
                }
                if (list.get(i).getFinishedWeldTime() != null) {
                    list.get(i).setFinishedWeldTime(list.get(i).getFinishedWeldTime().setScale(0, RoundingMode.HALF_UP));
                }

            }
            Integer count = acidEfficiencyDao.getAcidEfficiencyCount(request);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }

    }

    @Override
    public ResultData getReWeldList(ReWeldListReq request) {
        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<ReWeldListResp> list = acidEfficiencyDao.getReWeldList(page, request);

            Integer count = acidEfficiencyDao.getReWeldCount(request);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    @Override
    public ResultData getEarlyWarning() {
        List<EarlyWarningResp> list = acidEfficiencyDao.getEarlyWarning();
        return ResultData.ResultDataSuccess(list);
    }

    @Override
    public ResultData getDiffTime() {
        List<DiffTimeResp> list = acidEfficiencyDao.getDiffTime();
        return ResultData.ResultDataSuccess(list);
    }

    @Override
    public ResultData getRollChange(ChangeRollListReq request) {
        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<ChangeRollListResp> list = acidEfficiencyDao.getRollChange(page, request);

            Integer count = acidEfficiencyDao.getRollChangeCount(request);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    @Override
    public ResultData getUncoiler() {
        List<UncoilerResp> list = acidEfficiencyDao.getUncoiler();
        return ResultData.ResultDataSuccess(list);
    }

    @Override
    public void productionscheduleExcel(AcidEfficiencyListReq req, HttpServletResponse response) {
        Date d1 = new Date();
        AcidEfficiencyListReq roll = new AcidEfficiencyListReq();
        roll.setEntid(req.getEntid());
        roll.setStartDate(req.getStartDate());
        roll.setEndDate(req.getEndDate());

        List<AcidEfficiencyListResp> dbList = acidEfficiencyDao.getAcidEfficiencyLists(null, roll);
        Date d2 = new Date();
        log.info("查询用时：{}", (d2.getTime() - d1.getTime()) / 1000);
        Map<String, String> map = new HashMap<String, String>();
        map.put("A", "甲");
        map.put("B", "乙");
        map.put("C", "丙");
        map.put("D", "丁");
        List<ExcelProductionSchedule> list = new ArrayList<>();
        for (AcidEfficiencyListResp obj : dbList) {
            ExcelProductionSchedule excel = new ExcelProductionSchedule();
            BeanUtils.copyProperties(obj, excel);

            excel.setShift("1".equals(obj.getShift()) ? "白" : "夜");
            excel.setCrew(map.get(obj.getCrew()));

            excel.setOutMatWidth(excel.getOutMatWidth().setScale(3, BigDecimal.ROUND_HALF_UP));
            excel.setInMatThk(excel.getInMatThk().setScale(3, BigDecimal.ROUND_HALF_UP));
            excel.setOutMatThk(excel.getOutMatThk().setScale(3, BigDecimal.ROUND_HALF_UP));

            excel.setHeadToCutterTime(excel.getHeadToCutterTime() == null ? new BigDecimal(0) : excel.getHeadToCutterTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setArriveWaitPosTime(excel.getArriveWaitPosTime() == null ? new BigDecimal(0) : excel.getArriveWaitPosTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setAnotherheadToweldTime(excel.getAnotherheadToweldTime() == null ? new BigDecimal(0) : excel.getAnotherheadToweldTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setHeadCutTimesAct(excel.getHeadCutTimesAct() == null ? new BigDecimal(0) : excel.getHeadCutTimesAct().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setHeadCutTimesMax(excel.getHeadCutTimesMax() == null ? new BigDecimal(0) : excel.getHeadCutTimesMax().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setTailToweldTime(excel.getTailToweldTime() == null ? new BigDecimal(0) : excel.getTailToweldTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setFinishedWeldTime(excel.getFinishedWeldTime() == null ? new BigDecimal(0) : excel.getFinishedWeldTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setNotchTime(excel.getNotchTime() == null ? new BigDecimal(0) : excel.getNotchTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setArriceTrTime(excel.getArriceTrTime() == null ? new BigDecimal(0) : excel.getArriceTrTime().setScale(0, BigDecimal.ROUND_HALF_UP));

            excel.setWeldAdjustGapTime(excel.getWeldAdjustGapTime() == null ? new BigDecimal(0) : excel.getWeldAdjustGapTime().setScale(0, BigDecimal.ROUND_HALF_UP));


            excel.setPorExpandTimes(excel.getPorExpandTimes() == null ? new BigDecimal(0) : excel.getPorExpandTimes().setScale(0, BigDecimal.ROUND_HALF_UP));


            list.add(excel);
        }
        try {
            Map<String, Object> dataMap = new HashMap();
            dataMap.put("data", list);
            File file = ResourceUtils.getFile("classpath:exceltemplate\\酸轧生产时序统计.xlsx");
            TemplateExportParams templ = new TemplateExportParams(file.getPath(), false);
            Workbook workbook = ExcelExportUtil.exportExcel(templ, dataMap);
            ExcelUtilsPOI.exportExcel("酸轧生产时序统计", response, workbook);

            Date d3 = new Date();
            log.info("构建用时：{}", (d3.getTime() - d2.getTime()) / 1000);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResultData prodEfficiencySteelGrade(String beginDate, String endDate) {
        //钢种与产量
        Map<String, BigDecimal> steelOutputMap = new HashMap<>();
        List<Temp> steelOutputList = acidEfficiencyDao.selectSteelOutput(beginDate, endDate);
        for (Temp t : steelOutputList) {
            steelOutputMap.put(t.getK(), t.getV());
        }

        //生产效率
        List<TbTcm22280ProSpeed> list = acidEfficiencyDao.selectEff(beginDate, endDate);
        //按钢种分类
        Map<String, List<TbTcm22280ProSpeed>> steelEllMap = new HashMap<>();
        for (TbTcm22280ProSpeed e : list) {
            String steelGrade = e.getSteelgrade();
            if (!steelEllMap.containsKey(steelGrade)) {
                List<TbTcm22280ProSpeed> l = new ArrayList<>();
                l.add(e);
                steelEllMap.put(steelGrade, l);
            } else {
                steelEllMap.get(steelGrade).add(e);
            }
        }

        List<SteelGradeRateRes> resList = new ArrayList<>();
        //分别计算各钢种的生产效率
        for (Map.Entry<String, List<TbTcm22280ProSpeed>> entry : steelEllMap.entrySet()) {
            String steelGrade = entry.getKey();
            List<TbTcm22280ProSpeed> effList = entry.getValue();
            int zeroCount = 0;
            for (TbTcm22280ProSpeed eff : effList) {
                BigDecimal s5exSpeedLimit = eff.getS5exSpeedLimit();
                BigDecimal exSpeedMax = eff.getExSpeedMax();
                BigDecimal s5exSpeedL2Set = eff.getS5exSpeedL2Set();
                //S5EX_SPEED_LIMIT =0 时 EX_SPEED_MAX >= S5EX_SPEED_L2_SET*0.9
                if (s5exSpeedLimit.compareTo(BigDecimal.ZERO) == 0) {
                    if (exSpeedMax.compareTo(s5exSpeedL2Set.multiply(BigDecimal.valueOf(0.9))) >= 0) {
                        zeroCount++;
                    }
                } else {
                    //S5EX_SPEED_LIMIT 不是0时，EX_SPEED_MAX >= （ S5EX_SPEED_L2_SET | S5EX_SPEED_LIMIT 较小的*0.9）
                    BigDecimal jiaoxiao = s5exSpeedL2Set.compareTo(s5exSpeedLimit) > 0 ? s5exSpeedLimit : s5exSpeedL2Set;
                    if (exSpeedMax.compareTo(jiaoxiao.multiply(BigDecimal.valueOf(0.9))) >= 0) {
                        zeroCount++;
                    }
                }
            }
            SteelGradeRateRes res = new SteelGradeRateRes();
            res.setSteelGrate(steelGrade);
            res.setRate(BigDecimal.valueOf(zeroCount).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(effList.size()), 2, RoundingMode.HALF_UP));
            res.setOutputWt(steelOutputMap.get(steelGrade));
            resList.add(res);
        }
        Collections.sort(resList);
        List<String> xArr = new ArrayList<>();
        List<BigDecimal> outputArr = new ArrayList<>();
        List<BigDecimal> rateArr = new ArrayList<>();
        for (SteelGradeRateRes res : resList) {
            xArr.add(res.getSteelGrate());
            outputArr.add(res.getOutputWt());
            rateArr.add(res.getRate());
        }
        JSONObject obj = new JSONObject();
        obj.put("steelGrade", xArr);
        obj.put("outputWt", outputArr);
        obj.put("belowStandardRate", rateArr);

        return ResultData.ResultDataSuccess(obj);
    }


}
